/**
 * 自定义控件测试类
 * 用于模拟一个级联下拉框的情况
 * @Author wangjm
 * 2018-08-09
 */

define(["base/declare","jquery","widget/Widget","base/Data","lib/template","text!./ConcatSelect.template"],
    function(declare,$,Widget,Data,Template,_tpl){

    //下面三个函数用于模拟数据加载
        /**
         * 返回父下拉框数据列表
         */
        function loadMain(){
            return $.when([{"id":1,"name":1},{"id":2,"name":2},{"id":3,"name":3}]);
        }

        /**
         * 根据某一个大类加载子类数据列表
         * @param mainvalue
         */
        function loadSub(mainvalue){
            return $.when([{"id":mainvalue+"-1","name":mainvalue+"-1"},{"id":mainvalue+"-2","name":mainvalue+"-2"},{"id":mainvalue+"-3","name":mainvalue+"-3"}]);
        }

        /**
         * 根据子类id返回父类id
         * @param subid
         */
        function getMainId(subid){
            return $.when(subid.split("-")[0]);
        }


    return declare([Widget],{
        constructor: function(cfg){
            this.cfg = cfg;
            //用于加载数据是否
            this.loaded = new $.Deferred();
            this.tplRender = Template.compile(_tpl);
            var that = this;
            this.loaded.then(function(_d){
                that._dom = $(that.tplRender(_d));
                that._mainSel = $("select[data-name=mainselect]",that._dom);
                that._subSel = $("select[data-name=subselect]",that._dom);

                that._mainSel.on("change",function(){
                    that._subSel.html("<option value=''>请选择</option>");
                    var _mid = $(this).val();
                    if(_mid){
                        loadSub(_mid).then(function(slist){
                            for(var i=0;i<slist.length;i++){
                                that._subSel.append("<option value='"+slist[i].id+"'>"+slist[i].name+"</option>");
                            }
                        });
                    }
                });
            });

        },
        renderUI : function(_ctn){
            this._loadData(this.cfg.value);
            this.ctn = $(_ctn);
            this.ctn.empty();
            var that = this;
            this.loaded.then(function(){
                that.ctn.append(that._dom);
            })
        },
        setValue : function(_v){
            this._loadData(_v);
        },
        getValue: function(){
            return this._subSel?that._subSel.val():null;
        },
        _loadData : function(_v){
            var that = this;
            var _mainListDef = loadMain();
            var _mainIdDef ,_subDef;
            if(_v){
                _mainIdDef = getMainId(_v);
                _subDef = _mainIdDef.then(function(mainId){
                    return loadSub(mainId);
                });
            }
            $.when(_mainListDef,_mainIdDef,_subDef).then(function(mlist,mid,slist){
                that.loaded.resolve({mainList:mlist,mainId:mid,subList:slist,value:_v});
            });
        }
    });
});